<template>
	<xn-form-container
		:title="formData.id ? '编辑文件' : '上传文件'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="文件：" name="fileList" v-if="type == 0 && !formData.id">
				<a-spin :spinning="uploadLoading">
					<a-upload-dragger :file-list="formData.fileList" :before-upload="beforeUpload" @remove="handleRemove">
						<p class="ant-upload-drag-icon">
							<inbox-outlined></inbox-outlined>
						</p>
						<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
						<p class="ant-upload-hint">支持多个上传</p>
					</a-upload-dragger>
				</a-spin>
			</a-form-item>
			<template v-if="type == 1">
				<a-form-item label="地址：" name="fileUrl">
					<a-textarea placeholder="请输入地址" v-model:value="formData.fileUrl"></a-textarea>
				</a-form-item>
			</template>
			<a-form-item
				label="文件名称："
				name="file_name"
				:rules="{ required: true, message: '请输入文件名称', trigger: 'blur' }"
			>
				<a-input :maxlength="30" placeholder="请输入文件名称" v-model:value="formData.file_name"></a-input>
			</a-form-item>
			<a-form-item label="备注：" name="remark">
				<a-textarea placeholder="请输入备注" v-model:value="formData.remark" :maxlength="100"></a-textarea>
			</a-form-item>
			<a-form-item label="序号：" name="number">
				<a-input-number
					placeholder="请输入序号"
					v-model:value="formData.number"
					:min="0"
					:max="9999"
					style="width: 100%"
				></a-input-number>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { required, rules } from '@/utils/formRules'
	import dayjs from 'dayjs'
	import api from './api'
	import { globalStore } from '@/store/index'
	const store = globalStore()
	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({
		fileList: [],
		user_name: store.userInfo.user_name,
		file_name: '',
		fileUrl: '',
		date: dayjs().format('YYYY-MM-DD')
	})
	let index = 0
	const type = ref(0)
	// 打开抽屉
	const onOpen = (record = 0) => {
		if (![0, 1].includes(record)) {
			formData.value = {
				fileList: record.fileList,
				user_name: record.user_name,
				file_name: record.file_name,
				fileUrl: record.fileUrl,
				date: record.date,
				number: record.number,
				id: record.id,
				remark: record.remark
			}
			type.value = record.type
		} else {
			formData.value = {
				fileList: [],
				user_name: store.userInfo.user_name,
				file_name: '',
				fileUrl: '',
				date: dayjs().format('YYYY-MM-DD')
			}
			type.value = record
		}

		visible.value = true
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		visible.value = false
	}

	const checkUrl = (_rule, url) => {
		if (!url) {
			return Promise.reject('请输入url地址')
		}
		const pattern = new RegExp('^(https?|ftp):\\/\\/[^\\s/$.?#].[^\\s]*$', 'i')
		if (!pattern.test(url)) {
			return Promise.reject('请输入正确的url地址')
		} else {
			return Promise.resolve()
		}
	}

	// 默认要校验的
	const formRules = {
		service_module_id: [required('请输入服务模块')],
		time: [required('请选择时间范围')],
		status: [required('请选择状态')],
		fileUrl: [{ required: true, validator: checkUrl, trigger: 'blur' }]
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				api
					.submitForm(
						{
							...formData.value,
							...(formData.value.id
								? {
										create_time: dayjs(formData.value.create_time).format('YYYY-MM-DD HH:mm:ss')
								  }
								: {
										create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
								  }),
							type: type.value
						},
						formData.value.id
					)
					.then(() => {
						onClose()
						emit('successful')
					})
			})
			.catch((error) => {
				console.log(error)
			})
	}

	const uploadLoading = ref(false)

	const handleRemove = (file) => {
		const index = formData.value.fileList.indexOf(file)
		const newFileList = formData.value.fileList.slice()
		newFileList.splice(index, 1)
		formData.value.fileList = newFileList
	}

	const beforeUpload = (file) => {
		const fileData = new FormData()

		fileData.append('file', file)

		api.uploadFile(fileData).then((res) => {
			formData.value.file_name = file.name
			formData.value.fileUrl = res
			formData.value.fileList = [file]
			// onSubmit()
		})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
